let inp = document.querySelector("#tet")
let btn = document.querySelector(".but")
let add = document.querySelector(".header-right-1 .location")
let adc = document.querySelector(".middle-left h1 .location") 
let riqi = document.querySelector(".middle-left .times .data") 
let shijian = document.querySelector(".middle-left .times .time")
let tep = document.querySelector(".middle-left .weather .temp")
let minTep = document.querySelector(".middle-left .weather .min") 
let maxTep = document.querySelector(".middle-left .weather .max") 
let weatherText = document.querySelector(".middle-text") 
let Img = document.querySelector(".middle-left .weather .img1");
let p = document.querySelector(".middle .middle-left .middle-end .middle-end-p")
let sport = document.querySelector(".middle-right .middle-right-box:nth-child(1) .sport")
let car = document.querySelector(".middle-right .middle-right-box:nth-child(2) .car")
let yi = document.querySelector(".middle-right .middle-right-box:nth-child(3) .yi")
let yu = document.querySelector(".middle-right .middle-right-box:nth-child(4) .yu")
let shai = document.querySelector(".middle-right .middle-right-box:nth-child(5) .shai")
let lu = document.querySelector(".middle-right .middle-right-box:nth-child(6) .lu")
let Id = "";

window.onload = function () {
    inp.value = "青岛";
    weatherText.innerHTML = `
        <p>天气:<span class="txt1"></span></p>
        <p>空气质量:<span class="txt2"></span></p>
        <p>风向:<span class="txt3"></span></p>
        <p>风力:<span class="txt4"></span></p>
    `;
    setTimeout(() => btn.click(), 100);
    updateTimeWithSecond();
    setInterval(updateTimeWithSecond, 1000);
}

btn.onclick = function () {
    let xhr = new XMLHttpRequest();
    xhr.open("get", `https://pb5ctuk8qx.re.qweatherapi.com/geo/v2/city/lookup?location=${inp.value}&key=6698455b72b9408396c42145a42079a8`);
    xhr.send();
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && xhr.status == 200) {
            let data = JSON.parse(xhr.responseText);
            console.log("城市查询数据:", data);

            if (data.location && data.location.length > 0) {
                Id = data.location[0].id;
                add.innerHTML = inp.value;
                adc.innerHTML = inp.value;
                getNowWeather(Id); 
                get3dWeather(Id);
                getAirQuality(Id);
                getZhishu(Id);
            }
           
            localStorage.setItem("cityId", Id);
        }
    }
}
function getNowWeather(id) {
    let xhr = new XMLHttpRequest();
    xhr.open("get", `https://pb5ctuk8qx.re.qweatherapi.com/v7/weather/now?key=6698455b72b9408396c42145a42079a8&location=${id}`);
    xhr.send();
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && xhr.status == 200) {
            let wdata = JSON.parse(xhr.responseText);
            console.log("当前实时天气数据:", wdata);
            if (wdata.now) {
                tep.innerHTML = wdata.now.temp;
                let weatherCode = wdata.now.icon;
                Img.src =`../wearther/icon/${weatherCode}.png`; 
                let obsTime = wdata.now.obsTime;
                let [dateStr] = obsTime.split("T");
                let [year, month, day] = dateStr.split("-");
                let weekArr = ["日", "一", "二", "三", "四", "五", "六"];
                let week = weekArr[new Date(obsTime).getDay()];
                riqi.innerHTML = `${year}年${month.replace()}月${day.replace()}号 星期${week}`;

                let txt1 = document.querySelector(".txt1"); 
                let txt3 = document.querySelector(".txt3"); 
                let txt4 = document.querySelector(".txt4"); 
                if (txt1 && txt3 && txt4) {
                    txt1.innerHTML = wdata.now.text; 
                    txt3.innerHTML = wdata.now.windDir;
                    txt4.innerHTML = `${wdata.now.windScale}级`;
                }
            }
        }
    }
}

function get3dWeather(id) {
    let xhr = new XMLHttpRequest();
    xhr.open("get", `https://pb5ctuk8qx.re.qweatherapi.com/v7/weather/3d?key=6698455b72b9408396c42145a42079a8&location=${id}`);
    xhr.send();
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && xhr.status == 200) {
            let mixData = JSON.parse(xhr.responseText);
            if (mixData.daily && mixData.daily.length > 0) {
                let today = mixData.daily[0];
                minTep.innerHTML = today.tempMin;
                maxTep.innerHTML = today.tempMax;
            }
        }
    }
}
function getAirQuality(id) {
    let xhr = new XMLHttpRequest();
    xhr.open("get", `https://pb5ctuk8qx.re.qweatherapi.com/v7/air/now?key=6698455b72b9408396c42145a42079a8&location=${id}`);
    xhr.send();
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && xhr.status == 200) {
            let airData = JSON.parse(xhr.responseText);
            if (airData.now) {
                let txt2 = document.querySelector(".txt2");
                if (txt2) {
                    txt2.innerHTML = `${airData.now.category} `; 
                }
            }
        }
    }
}
function getZhishu(id) {
    let xhr = new XMLHttpRequest();
    xhr.open("get", `https://pb5ctuk8qx.re.qweatherapi.com/v7/indices/1d?key=6698455b72b9408396c42145a42079a8&location=${id}&type=1,2,3,4,5,6`);
    xhr.send();
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && xhr.status == 200) {
            let Zhishu = JSON.parse(xhr.responseText);
            console.log("生活指数数据:", Zhishu);
            if (Zhishu.daily && Zhishu.daily.length >= 6) {
                p.innerHTML = Zhishu.daily[2].text
                sport.innerHTML = Zhishu.daily[0].category 
                car.innerHTML = Zhishu.daily[1].category 
                yi.innerHTML = Zhishu.daily[2].category 
                yu.innerHTML = Zhishu.daily[3].category 
                shai.innerHTML = Zhishu.daily[4].category 
                lu.innerHTML = Zhishu.daily[5].category 
            } 
            
        }
    }
}


function updateTimeWithSecond() {
    let now = new Date();
    let h = now.getHours() < 10 ? `0${now.getHours()}` : now.getHours();
    let m = now.getMinutes() < 10 ? `0${now.getMinutes()}` : now.getMinutes();
    let s = now.getSeconds() < 10 ? `0${now.getSeconds()}` : now.getSeconds();
    shijian.innerHTML = `${h}:${m}:${s}`;
}

document.addEventListener('DOMContentLoaded', function() {
  let more = document.getElementById('more');
  if (more) { 
    more.onclick = function() {
      const cityId = Id || localStorage.getItem("cityId");
      if (cityId) {
        window.open(`./更多天气.html?location=${cityId}`);
      } else {
        console.error("没有找到城市ID");
  
        alert("请先选择一个城市");
      }
    };
  }
});
